﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WMPLib;

namespace ClassicJukebox
{
    public class WMPMediaLibraryRepository : IMediaLibraryRepository
    {
        public IList<Album> GetAlbums()
        {
            List<Album> albums = new List<Album>();

            WindowsMediaPlayer wmp = new WindowsMediaPlayer();
            IWMPPlaylist playlist = wmp.mediaCollection.getAll();
            for (int i = 0; i < playlist.count; i++)
            {
                IWMPMedia media = (IWMPMedia)playlist.get_Item(i);

                Track track = new Track();
                track.Title = media.getItemInfo("Title");
                track.Location = media.getItemInfo("SourceUrl");
                track.Number = media.getItemInfo("OriginalIndex");

                string albumName = media.getItemInfo("Album");

                var album = (from a in albums
                             where a.Name == albumName
                             select a).FirstOrDefault();

                if (album != null)
                {
                    album.Tracks.Add(track);
                }
                else
                {
                    Album a = new Album();
                    a.Name = albumName;

                    string dir = System.IO.Path.GetDirectoryName(track.Location);
                    string path = System.IO.Path.Combine(dir, "Folder.jpg");
                    if(File.Exists(path))
                    {
                        a.Cover = path;
                    }

                    a.Artist = media.getItemInfo("AlbumArtist");
                    a.Tracks.Add(track);

                    if (albumName != string.Empty)
                    {
                        albums.Add(a);
                    }
                }
            }

            return albums;
        }
    }
}
